﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace EM.FrameWork
{
    public static partial class Common
    {

        #region 合并复合对象

        /// <summary>合并复合对象</summary>
        /// <param name="complexObj">复合对象，对象本身以及分离的对象</param>
        public static List<T> GenerateComplexObject<T>(IEnumerable complexObj) where T : class
        {
            List<T> listT = new List<T>();
            foreach (var complex in complexObj)
            {
                listT.Add(GenerateComplexObject<T>(complex));
            }
            return listT;
        }

        /// <summary>合并复合对象</summary>
        /// <param name="complex">复合对象，对象本身以及分离的对象</param>
        public static T GenerateComplexObject<T>(object complex) where T : class
        {
            if (complex == null) return null;

            T t = default(T);
            PropertyInfo[] propertyInfos = complex.GetType().GetProperties();
            var proT = propertyInfos.Where(p => p.PropertyType.FullName == typeof(T).FullName).First();
            t = (T)proT.GetValue(complex, null);

            System.Reflection.PropertyInfo[] propertyElse = typeof(T).GetProperties();
            foreach (var temp in propertyInfos)
            {
                IEnumerable<PropertyInfo> existPro = propertyElse.Where(p => p.Name == temp.Name);
                if (existPro.Count() == 0)
                    continue;
                PropertyInfo proElse = existPro.First();
                proElse.SetValue(t, temp.GetValue(complex, null), null);//?? DefaultByType(temp.PropertyType)
            }

            return t;
        }

        #endregion
    }
}
